/*****  Component, by Ben Bi <prince.bi@gmail.com>  created at: 12/23/2009 4:10:45 PM  *****/

/***** variables declartion section, begin *****/
$.jgrid.no_legacy_api = true;
$.jgrid.useJSON = true;

var mainLayout, appTabs, appStorehouseLayout, appSystemManagementLayout;
var showResizeMsgs = false;
var msg;
/***** variables declartion section, end *****/

/***** init section, begin *****/
$(document).ready(
    function() {
       wacShowBlockUILoading();

       initLayouts();

       bindDefaultEvents();

       wacHideBlockUI();

    }
    );

function bindDefaultEvents()
{
    $('#appStorehouseMenuTabs').bind('wacOrderSearch', function(event) {
        wacDebugLog(event.rawId+ " : " + event.orderCode);
        $("#appStorehouseMenu").setSelection(event.rawId);
    });

    $('#appStorehouseMenuTabs').bind('tabsremove', function(event, ui) {
        wacDebugLog($(event.target).attr("id") + ": tabsremove id: " + ui.panel.id);
    });

    $('#appStorehouseMenuTabs').bind(
        'tabsload',
        function (event, ui)
        {
            wacHideBlockUI();
            wacDebugLog("tabsload: ");
            wacDebugLog(event.currentTarget.id);
            wacDebugLog($.dump(event.currentTarget.id));
        }
        );

    $('#appStorehouseMenuTabs').bind(
        'tabsadd',
        function (event, ui)
        {
            wacShowBlockUILoading();
            wacDebugLog($(event.target).attr("id") + ": tabsadd id: " + ui.panel.id);
//            wacDebugLog("tabsadd");
        }
    );

    $('#wacAppBody').bind(
        'dialogopen',
        function (event, ui)
        {
            wacDebugLog("dialogopen id: " + $(event.target).attr("id"));
        }
    );

}

function initLayouts()
{
    // best to create the tabs first, because is 'container' for the tab-layout (appStorehouse)
    appTabs = $("#appTabs").tabs({
        show: resizeTabLayout // resize layout EACH TIME the layout-tab becomes 'visible'
    });
    
    // use different outer-layout classNames to simplify/clarify CSS
    mainLayout = $('body').layout({
        name: "mainLayout"
        ,
        triggerEventsOnLoad:  false
        ,
        north__paneSelector:  "#appTabBtns"
        ,
        center__paneSelector:  "#appContainer"
        ,
        south__paneSelector:  "#footer"
        //            ,
        //            center__onresize:   "appStorehouseLayout.resizeAll"
        ,
        spacing_open:   0
    });

    // resize div.ui-layout-ui-widget-content AFTER initializing the tabs
    mainLayout.resizeAll();
    
    // set jgrid default setting
    $.jgrid.defaults = $.extend($.jgrid.defaults,{
        loadui:"enable"
    });

    // initialize app storehouse layout
    initAppStorehouseLayout();
    // initialize app system management layout
    initAppSystemManagementLayout();

    initContextMenu();

    initFloatingBox();

}

function resizeTabLayout ()
{
    if (!appTabs) return; // make sure tabs are initialized
    var selected = appTabs.tabs('option', 'selected');
    // ONLY resize the layout when first tab is 'visible'
    //    if (selected === 1) { // Tab #2 (index=1)
    msg = "";
    timer('page', 'reset'); // init timer
    timer( null , 'clear'); // clear timer

    // now resize the outermost layout to fit the new container size...
    mainLayout.resizeAll(); // ...triggers cascading resize of inner-layouts - if initialized
    msg += "\n----------------------------------------------\n"+ timer('page')
    + " - resizeTabLayout - mainLayout.resizeAll \n";

    // make sure all inner-layouts are initialized and 'visible'
    initAppStorehouseLayout();
    initAppSystemManagementLayout();
}

function initAppStorehouseLayout ()
{
    // make sure Container element is not hidden
    $('#appStorehouse').show();

    // if Container is still not visible, then must be INSIDE a hidden element
    if ( !$('#appStorehouse').is(':visible') ) return; // ABORT

    // init the Layout if not already done
    //    if (!appStorehouseLayout)
    appStorehouseLayout = $('#appStorehouse').layout({
        name: "appStorehouseLayout"
        ,
        resizeWithWindow:   false
        ,
        triggerEventsOnLoad:  false
        ,
        center__paneSelector:  "#appStorehouseRightPane"
        ,
        west__paneSelector:   "#appStorehouseLeftPane"
        //            ,
        //            contentSelector:   ".ui-widget-content"
        ,
        spacing_open: 4
        ,
        spacing_closed: 4
        ,
        west__size: 200
        ,
        west__initClosed: false
        ,
        south__minSize: 5
        //, south__size:    22
        ,
        south__size: 'auto'
        ,
        south__togglerLength_open: 0
        ,
        south__togglerLength_close: -1
        ,
        south__resizable: false
        ,
        south__slidable: false
        ,
        south__spacing_open:  1
        ,
        center__onresize:   "InnerLayout.resizeAll"
        ,
        onresizeall_start: function () {
            if (showResizeMsgs) alert( 'appStorehouseLayout.onresizeall_start()' );
        }
        ,
        onresizeall_end: function () {
            if (showResizeMsgs) alert( 'appStorehouseLayout.onresizeall_end()' );
        },
        west__onresize: function (pane, $Pane) {
            $("#appStorehouseMenu").jqGrid('setGridWidth',$Pane.innerWidth()-2);
        }
    });

    var appStorehouseMainTab =$('#appStorehouseMenuTabs','#appStorehouseRightPane').tabs({
        add: function(e, ui) {
            // append close thingy
            $(ui.tab).parents('li:first')
            .append('<span class="ui-tabs-close ui-icon ui-icon-close" title="Close Tab"></span>')
            .find('span.ui-tabs-close')
            .click(function() {
                appStorehouseMainTab.tabs('remove', $('li', appStorehouseMainTab).index($(this).parents('li:first')[0]));
            });
            // select just added tab
            appStorehouseMainTab.tabs('select', '#' + ui.panel.id);
        }
    });

    $("#appStorehouseMenu").jqGrid({
        url: BASE_URL + "/default/getAppStorehouseMenu",
//        url: "/app_storehouse_menu.xml",
//        url: "/app_storehouse_menu_1.xml",
        datatype: "xml",
        height: "auto",
        pager: false,
        loadui: "disable",
        colNames: ["id","生产流程选项","url"],
        colModel: [
        {
            name: "id",
            width:1,
            hidden:true,
            key:true
        },
        {
            name: "menu",
            width: 180,
            resizable: false,
            sortable:false
        },
        {
            name: "url",
            width:1,
            hidden:true
        }
        ],
        treeGrid: true,
        caption: "生产流程管理菜单",
        ExpandColumn: "menu",
        autowidth: true,
        //            width: 180,
        rowNum: 200,
        ExpandColClick: true,
        treeIcons: {
            leaf:'ui-icon-document-b'
        },
        onSelectRow: function(rowid) {
            var treedata = $("#appStorehouseMenu").jqGrid('getRowData',rowid);
            if(treedata.isLeaf=="true") {
                //treedata.url
                var st = "#t"+treedata.id;
                if($(st).html() != null ) {
                    appStorehouseMainTab.tabs('select',st);
                } else {
                    appStorehouseMainTab.tabs('add',st, treedata.menu);
                    $(st,"#appStorehouseMenuTabs").load(treedata.url);
                }
            }
        }
    });
}

  function initAppSystemManagementLayout ()
{
    // make sure Container element is not hidden
    $('#appSystemManagement').show();

    // if Container is still not visible, then must be INSIDE a hidden element
    if ( !$('#appSystemManagement').is(':visible') ) return; // ABORT

    // init the Layout if not already done
    //    if (!appSystemManagementLayout)
    appSystemManagementLayout = $('#appSystemManagement').layout({
        name: "appSystemManagementLayout"
        ,
        resizeWithWindow:   false
        ,
        triggerEventsOnLoad:  false
        ,
        center__paneSelector:  "#appSystemManagementRightPane"
        ,
        west__paneSelector:   "#appSystemManagementLeftPane"
        //            ,
        //            contentSelector:   ".ui-widget-content"
        ,
        spacing_open: 4
        ,
        spacing_closed: 4
        ,
        west__size: 200
        ,
        west__initClosed: false
        ,
        south__minSize: 5
        //, south__size:    22
        ,
        south__size: 'auto'
        ,
        south__togglerLength_open: 0
        ,
        south__togglerLength_close: -1
        ,
        south__resizable: false
        ,
        south__slidable: false
        ,
        south__spacing_open:  1
        ,
        center__onresize:   "InnerLayout.resizeAll"
        ,
        onresizeall_start: function () {
            if (showResizeMsgs) alert( 'appSystemManagementLayout.onresizeall_start()' );
        }
        ,
        onresizeall_end: function () {
            if (showResizeMsgs) alert( 'appSystemManagementLayout.onresizeall_end()' );
        },
        west__onresize: function (pane, $Pane) {
            $("#appSystemManagementMenu").jqGrid('setGridWidth',$Pane.innerWidth()-2);
        }
    });

    var appSystemManagementMainTab =$('#appSystemManagementMenuTabs','#appSystemManagementRightPane').tabs({
        add: function(e, ui) {
            // append close thingy
            $(ui.tab).parents('li:first')
            .append('<span class="ui-tabs-close ui-icon ui-icon-close" title="Close Tab"></span>')
            .find('span.ui-tabs-close')
            .click(function() {
                appSystemManagementMainTab.tabs('remove', $('li', appSystemManagementMainTab).index($(this).parents('li:first')[0]));
            });
            // select just added tab
            appSystemManagementMainTab.tabs('select', '#' + ui.panel.id);
        }
    });

    $("#appSystemManagementMenu").jqGrid({
        url: BASE_URL + "/default/getSystemManagementMenu",
//        url: "/system_management_menu.xml",
        datatype: "xml",
        height: "auto",
        pager: false,
        loadui: "disable",
        colNames: ["id","选项","url"],
        colModel: [
        {
            name: "id",
            width:1,
            hidden:true,
            key:true
        },
        {
            name: "menu",
            width: 180,
            resizable: false,
            sortable:false
        },
        {
            name: "url",
            width:1,
            hidden:true
        }
        ],
        treeGrid: true,
        caption: "管理菜单",
        ExpandColumn: "menu",
        autowidth: true,
        //            width: 180,
        rowNum: 200,
        ExpandColClick: true,
        treeIcons: {
            leaf:'ui-icon-document-b'
        },
        onSelectRow: function(rowid) {
            var treedata = $("#appSystemManagementMenu").jqGrid('getRowData',rowid);
            if(treedata.isLeaf=="true") {
                //treedata.url
                var st = "#t"+treedata.id;
                if($(st).html() != null ) {
                    appSystemManagementMainTab.tabs('select',st);
                } else {
                    appSystemManagementMainTab.tabs('add',st, treedata.menu);
                    $(st,"#appSystemManagementMenuTabs").load(treedata.url);
                }
            }
        }
    });
}

function initContextMenu()
{
    $('#appStorehouseContextMenu').maxZIndex();
//    $('#wacAppBody').vscontext({
//        menuBlock: 'vs-context-menu', offsetX : -5,offsetY : -5, speed : 'fast'
//    });

    $('#wacAppBody').jeegoocontext('appStorehouseContextMenu', {
                widthOverflowOffset: 0,
                heightOverflowOffset: 3,
                submenuLeftOffset: -4,
                submenuTopOffset: -5
            });
}

function initFloatingBox()
{
    $("#floatingToolBar").show();
    $("#floatingToolBar").floating({targetX:"right", targetY:"top"});

    $("#floatingPanel").hide();
//    $("#floatingPanel").floating({targetX:"right", targetY:"bottom"});
    $("#floatingPanel").floating({targetX:"right", targetY:-400});
}

function timer (timerName, valName) {
    var
    name = timerName || 'debugTimer'
    , Timer = window[ name ]
    ;

    // init the timer first time called
    if (!Timer || valName == 'reset') {
        Timer = window[ name ] = {};
        Timer.start = new Date();
        Timer.last = new Date();
        Timer.step = 0; // time since 'last'
        Timer.total = 0; // time since 'start'
    }
    else if (valName == 'clear') {
        window[ name ] = null;
    }
    else {
        Timer.step = (new Date()) - Timer.last;  // time since 'last'
        Timer.total = (new Date()) - Timer.start; // time since 'start'
        Timer.last = new Date();
    }

    var time = (valName == 'total') ? Timer.total : Timer.step;
    time += ""; // to string

    // pad time to 4 chars with underscores
    switch (time.length) {
        case 1:time = "&ensp;&ensp;&ensp;"+ time;break;
        case 2:time = "&ensp;&ensp;"+ time;break;
        case 3:time = "&ensp;"+ time;break;
    }

    return time;
};
/***** init section, end *****/

